// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
axios.defaults.baseURL = 'http://139.199.203.14:4000';
cloud.init()

const db = cloud.database()

const playlistCollection = db.collection('playlist')
const musiclistCollection = db.collection('musiclist')
const songCollection = db.collection('song')
const lyricCollection = db.collection('lyric')
const TcbRouter = require('tcb-router')
// 云函数入口函数
exports.main = async (event, context) => {
  let app = new TcbRouter({event})
  //获取推荐歌单列表
  app.router('playlist',async (ctx,next) => {
    let {data} = await playlistCollection
      .skip((event.page - 1) * event.limit)
      .limit(event.limit)
      .orderBy('createTime','desc').get();
    ctx.body = data
  })
  //获取歌单列表
  app.router('playlistDetail', async (ctx,next) => {
    let {data} = await musiclistCollection.where({
      id:event.playlistId
    }).get()
    if (data.length > 0) {
      ctx.body = data[0]
    } else {
      let {data:res} = await axios.get(`/playlist/detail?id=${event.playlistId}`)
      if (res.code === 200) {
        let pl = res.playlist
        let tracks = pl.tracks.map(item => ({
          name:item.name,
          ar:item.ar,
          alia:item.alia,
          id:item.id,
          picUrl:item.al.picUrl
        }))
        let data = {
          tracks,
          coverImgUrl:pl.coverImgUrl,
          description:pl.description,
          tags:pl.tags,
          name:pl.name,
          id:pl.id
        }
        await musiclistCollection.add({
          data
        })
        ctx.body = data
      } else {
        throw new Error('third Error')
      }
    }
  })
  //获取歌曲播放地址
  app.router('musicSrc', async (ctx,next) => {
    let musicId = +event.musicId
    let {data} = await songCollection.where({id:musicId}).get()
    if (data && data.length > 0) {
      if (data[0].expi > Date.now()) {
        return ctx.body = data[0]
      } else {
        await songCollection.where({id:musicId}).remove()
      }
    }
    let {data:res} = await axios.get(`/song/url?id=${musicId}`)
      if (res.code === 200) {
        let obj = res.data[0]
        obj.expi = Date.now() + (obj.expi - 10) * 1000
        await songCollection.add({
          data:obj
        })
        ctx.body = res.data[0]
      } else {
        throw new Error('get music url fail:',err)
      }
  })
  //获取歌词
  app.router('lyric', async (ctx,next) => {
    let musicId = event.musicId
    let {data} = await lyricCollection.where({id:musicId}).get()
    if (data && data.length > 0) {
      ctx.body = data[0]
    } else {
      let {data:res} = await axios.get(`/lyric?id=${musicId}`)
      if (res.code === 200) {
        let obj = res.lrc
        obj.id = musicId
        await lyricCollection.add({
          data:obj
        })
        ctx.body = res.lrc
      } else {
        throw new Error('get lyric fail:',err)
      }
    }
  })
  return app.serve()
}